//
//  ChatViewController.m
//  Closer
//
//  Created by zhangkai on 16/3/10.
//  Copyright © 2016年 Closer_All. All rights reserved.
//

#import "ChatViewController.h"
#import <EaseMobSDKFull/EaseMob.h>
#import "ChatCell.h"
#import "User.h"
#define ChatCell_id @"ChatCell_id"
@interface ChatViewController ()<EMChatManagerDelegate,EMCallManagerDelegate,UITableViewDataSource,UITableViewDelegate
>
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (weak, nonatomic) IBOutlet UITextField *inputText;
- (IBAction)sendButton:(id)sender;

@property(nonatomic,strong)NSMutableArray  *dataArray;
@property(nonatomic,strong)EMConversation *conversation ;

@end

@implementation ChatViewController

- (instancetype)initWithChatter:(NSString *)chatter isGroup:(BOOL)isGroup{
    
    EMConversationType type=isGroup?eConversationTypeGroupChat:eConversationTypeChat;
    self =[self initWithChatter:chatter conversationType:type];
    return self;
}
-(instancetype)initWithChatter:(NSString *)chatter conversationType:(EMConversationType)conversationType{
    
    self=[super initWithNibName:@"ChatViewController" bundle:nil];
    if (self) {
        
        _conversation = [[EaseMob sharedInstance].chatManager conversationForChatter:chatter  conversationType:conversationType];
          _conversation.enableUnreadMessagesCountEvent=YES;
        [_conversation markAllMessagesAsRead:YES];
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self addObserverOfTextField];
    self.tableView.delegate=self;
    self.tableView.dataSource=self;
    [self.tableView registerNib:[UINib nibWithNibName:@"ChatCell" bundle:nil] forCellReuseIdentifier:ChatCell_id];
    //建立连接
    [[EaseMob sharedInstance].chatManager addDelegate:self delegateQueue:nil];
    [[ EaseMob sharedInstance].callManager addDelegate:self delegateQueue:nil];
  
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    
}
-(void)viewWillAppear:(BOOL)animated{
    
    [super viewWillAppear:animated];
     long long timestamp = [[NSDate date] timeIntervalSince1970] * 1000 + 1;
    
    self.dataArray=[NSMutableArray arrayWithArray:[self.conversation loadNumbersOfMessages:4 before:timestamp ]];
    
}
#pragma mark - 观察者通知键盘事件
-(void)addObserverOfTextField{
    NSNotificationCenter *notificationCenter=[NSNotificationCenter defaultCenter];
    [notificationCenter addObserver:self selector:@selector(keyboardShow:) name:UIKeyboardWillShowNotification object:nil];
    [notificationCenter addObserver:self selector:@selector(keyboardHidden:) name:UIKeyboardWillHideNotification object:nil];
}
-(void)keyboardShow:(NSNotification*)notification{
    CGRect rect=[[[notification userInfo] objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue] ;
    [UIView animateWithDuration:2 animations:^{
        self.view.frame=CGRectMake(0,-rect.size.height,self.view.bounds.size.width,self.view.bounds.size.height);
    }];
}
-(void)keyboardHidden:(NSNotification*)notification{
    [UIView animateWithDuration:2 animations:^{
        self.view.frame=CGRectMake(0,0,self.view.bounds.size.width,self.view.bounds.size.height);
    }];
}

-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    [self.view endEditing:NO];
}

#pragma mark - 发送消息
- (IBAction)sendButton:(id)sender {
    EMChatText *txtChat = [[EMChatText alloc] initWithText:self.inputText.text];
    EMTextMessageBody *body = [[EMTextMessageBody alloc] initWithChatObject:txtChat];
    EMMessage *message = [[EMMessage alloc] initWithReceiver:self.conversation.chatter bodies:@[body]];
    
    switch (self.conversation.conversationType) {
        case eConversationTypeGroupChat:
             message.messageType = eMessageTypeGroupChat;
            break;
        case eConversationTypeChat:
            message.messageType = eMessageTypeChat;
            break;
        default:
            break;
    }
    EMError *error=nil;
    [[EaseMob sharedInstance].chatManager sendMessage:message progress:nil error:&error];
    if (!error) {
        [self.dataArray addObject:message];
        [self.tableView reloadData];
    }
    else{
        NSLog(@"%@",error);
    }
}
#pragma mark - 接受在线消息
- (void)didReceiveMessage:(EMMessage *)message{
        NSLog(@"用户消息%@",self.conversation.chatter);
    if ([self.conversation.chatter isEqualToString:message.from]) {
        NSLog(@"用户消息%@",self.conversation.chatter);
        
        [self.dataArray addObject: message];
        [self.tableView reloadData];
    }
}

#pragma mark - 未读在线消息
- (void)didUnreadMessagesCountChanged{
    
    NSLog(@"未读消息发生变化");
}
#pragma mark - 接受离线消息
- (void)willReceiveOfflineMessages{
    NSLog(@"将要接受离线消息");
}
- (void)didReceiveOfflineMessages:(NSArray *)offlineMessages{
    NSLog(@"将要接受离线列表");
    
}
- (void)didFinishedReceiveOfflineMessages{
    NSLog(@"完成接受离线消息");
}


#pragma  mark  - table 代理事件
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.dataArray.count;
}
-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    ChatCell *chatCell=[tableView dequeueReusableCellWithIdentifier:ChatCell_id];
    
    EMMessage *message=  self.dataArray[indexPath.row];
    id<IEMMessageBody> msgBody = message.messageBodies.firstObject;
    chatCell.chatText.text=((EMTextMessageBody *)msgBody).text;
    if ([message.from isEqualToString:self.conversation.chatter]) {
        chatCell.chatText.textAlignment=NSTextAlignmentLeft;
    }else{
        chatCell.chatText.textAlignment=NSTextAlignmentRight;
    }
    return chatCell;
}

@end
